<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>shadow dom</title>
<link href="./css/view.css" rel="stylesheet">
</head>

<body>
  <div style="width: 1000px; margin: 0 auto;">
    <p>
      <button id="btn-create">create editor</button>
      <button id="btn-toggle-enable">disable/enable</button>
      <button id="btn-destroy">destroy editor</button>
      <button id="btn-wang-editor-dom">remove wang-editor dom</button>
    </p>

    <!-- 编辑器 -->
    <div id="editor-container">
      <wang-editor></wang-editor>
    </div>

    <!-- 内容状态 -->
    <p style="background-color: #f1f1f1;">
      当前文字数量：<span id="total-length"></span>；
      选中文字数量：<span id="selected-length"></span>；
      选中文字："<span id="selected-text"></span>"
    </p>

    <!-- 显示内容 -->
    <div id="editor-content-view" class="editor-content-view"></div>
  </div>

  <script src="js/init-content.js"></script>
  <script src="../dist/index.js"></script>
  <script>
    let editor, toolbar
    const editorContainer = document.querySelector('#editor-container')

    const editorConfig = { MENU_CONF: {} }
    // editorConfig.autoFocus = false
    // editorConfig.readOnly = true
    // editorConfig.scroll = false
    editorConfig.placeholder = '请输入内容'
    editorConfig.MENU_CONF['uploadImage'] = {
      server: 'http://106.12.198.214:3000/api/upload-img', // 上传图片地址
      fieldName: 'index-fileName'
    }
    console.log('测试上传图片，请使用 upload-image.html')
    editorConfig.onCreated = (editor) => {
      console.log('on created', editor)
    }
    editorConfig.onChange = (editor) => {
      const html = editor.getHtml()
      document.getElementById('editor-content-view').innerHTML = html

      // 选中文字
      const selectionText = editor.getSelectionText()
      document.getElementById('selected-text').innerHTML = selectionText
      document.getElementById('selected-length').innerHTML = selectionText.length
      // 全部文字
      document.getElementById('total-length').innerHTML = editor.getText().length
    }
    editorConfig.onDestroyed = (editor) => {
      console.log('on destroyed', editor)
    }
    editorConfig.onFocus = (editor) => {
      console.log('onFocus', editor)
    }
    editorConfig.onBlur = (editor) => {
      console.log('onBlur', editor)
    }

    class WangEditorElement extends HTMLElement {
      constructor() {
        super()
        this.attachShadow({ mode: 'open' })
        this.shadowRoot.innerHTML = `
          <link href="https://cdn.bootcdn.net/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet">
          <link href="./css/editor.css" rel="stylesheet">
          <link href="../dist/css/style.css" rel="stylesheet">
          <div>
            <div id="editor-toolbar" class="editor-toolbar"></div>
            <div id="editor-text-area" class="editor-text-area"></div>
          </div>
        `
      }
      create() {
        // 创建编辑器
        editor = window.wangEditor.createEditor({
          selector: this.shadowRoot.querySelector('#editor-text-area'),
          config: editorConfig,
          content: [], // 默认内容，下文有解释
          mode: 'default' // 或者 'simple' ，下文有解释
        })

        // 创建工具栏
        toolbar = window.wangEditor.createToolbar({
          editor,
          selector: this.shadowRoot.querySelector('#editor-toolbar'),
          mode: 'default' // 或者 'simple' ，下文有解释
        })

        this.editor = editor
        this.toolbar = toolbar
      }

      destroy() {
        this.editor.destroy()
      }
    }

    // customElements define
    let wangEditorExample
    customElements.define('wang-editor', class WangEditor extends WangEditorElement {
      constructor() {
        super()
        wangEditorExample = this
      }

      connectedCallback() {
        console.log('首次被插入文档DOM时调用。');
        this.create()
      }

      disconnectedCallback() {
        console.log('从文档DOM中删除时调用');
        this.destroy()
      }

      adoptedCallback() {
        console.log('移动到新的文档时调用');
      }

      attributeChangedCallback() {
        console.log('增加、删除、修改自身属性被调用');
      }
    })


    // create
    document.getElementById('btn-create').addEventListener('click', () => {
      // wangEditorExample.create()
      if (editorContainer.children.length) {
        wangEditorExample.create()
      } else {
        editorContainer.append(document.createElement('wang-editor'))
      }
    })
    console.log(`如果页面没有编辑器，点击 'create' 按钮创建`)

    // toggle enable
    document.getElementById('btn-toggle-enable').addEventListener('mousedown', (e) => {
      // 使用 mousedown ，且 preventDefault ，否则触发编辑器 blur ，导致无法正确 focus
      // TODO 文档中说明（以及其他的 editState）
      e.preventDefault()

      if (editor.getConfig().readOnly) {
        editor.enable()
      } else {
        editor.disable()
      }
    })

    // destroy
    document.getElementById('btn-destroy').addEventListener('click', () => {
      editor.destroy()
      editor = undefined
    })

    // btn-wang-editor-dom
    document.getElementById('btn-wang-editor-dom').addEventListener('click', () => {
      const editorElement = document.querySelector('wang-editor')
      if (editorElement) {
        editorElement.parentElement.removeChild(editorElement)
      }
    })
  </script>
</body>

</html>